package edu.hcmus.sow.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.DefaultPermissionFactory;
import org.springframework.security.acls.domain.PermissionFactory;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.hcmus.sow.dao.RepositoryDAO;
import edu.hcmus.sow.domain.Repository;
import edu.hcmus.sow.domain.security.CustomPrincipalSid;
import edu.hcmus.sow.service.SecurityService;

@Controller
public class SecurityController {

   @Autowired
   private RepositoryDAO repositoryDAO;

   @Autowired
   private SecurityService securityService;

   private PermissionFactory permissionFactory = new DefaultPermissionFactory();

   @RequestMapping("/listRepositories")
   public ModelAndView listRepositories() {
      ModelAndView mav = new ModelAndView();

      mav.addObject("repositories", repositoryDAO.findAll());

      mav.setViewName("test");

      return mav;
   }
   
   @RequestMapping("/addPermission")
   public String addPermission(@RequestParam Integer repositoryId) {
      Repository repository = repositoryDAO.findById(repositoryId);

      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      CustomPrincipalSid sid = new CustomPrincipalSid(auth);
      Permission permission = permissionFactory.buildFromMask(BasePermission.READ.getMask());

      securityService.addPermission(repository, sid, permission);

      return "hello";
   }

}
